var express = require('express');
var router = express.Router();
const jwt = require('jsonwebtoken');
var { secretKey, sha256 } = require('../utils/token');
const adminService = require('../service/adminService');


// 管理员登录
router.get('/login', async function (req, res) {
    let { account, password } = req.query;
    let data = await adminService.login(account, sha256(password));
    // let data = await adminService.login(account, password);
    // token 验证
    if (Object.keys(data).length > 0) {
        // 生成 token
        let authToken = jwt.sign({ user: data }, secretKey);
        res.send({ token: authToken, data });
        return;
    }
    // res.send(data);

});
// 门店管理员注册
router.post('/register', async function (req, res) {
    // status 给一个“申请中”的默认值
    let admin = await adminService.findAdmin(req.query);
    // 如果找到了就返回一个状态值（前台根据状态值来控制是否注册）
    if (admin.length) {
        res.send({ state: "true" });
        return;
    }
    // 不存在就注册
    else {
        let { account, password, name, age, gender, phone, position, status } = req.query;
        let data = await adminService.register({ account, password: sha256(password), name, age, gender, phone, position: position || 1, status: status || 0 })
        res.send(data);
    }
}),

    //查询所有管理员
    router.get('/', async function (req, res) {
        let { type, value, current, size } = req.query;
        let searchObj = {};
        //模糊查询
        if (type) {
            if (type == "age" || "gender" || "phone" || "position" || "status") {
                searchObj[type] = { $regex: value };
            }
        };
        let data = await adminService.find(searchObj,
            { current: current || 1, size: size || 10000 });
        res.send(data);
    });

//根据ID查询管理员
router.get('/:id', async function (req, res) {
    let id = req.params.id;
    let data = await adminService.findById(id);
    res.send(data);
});

//增加管理员
router.post('/', async function (req, res) {
    let { account, password, name, age, gender, phone, position, status } = req.body;
    let data = await adminService.insert({ account, password: sha256(password), name, age, gender, phone, position: position || 0, status: status || 0 });
    res.send(data);
});

//修改管理员
router.put('/:id', async function (req, res) {
    let id = req.params.id;
    let data = await adminService.update(id, req.body);
    console.log(data);
    res.send(data);
});

//根据ID删除管理员
router.delete('/:id', async function (req, res) {
    let data = await adminService.delete(req.query);
    res.send("data");
});


module.exports = router;